/*
 A class to hold a canvas polygon, consisting of canvas points.
 
 Requirements:
 - The canvas.js script file.
 - The canvasPoint.js script file.
 */

const polygonRadius = 100;

// initializes the polygon to be nothing.
function Polygon2D() {
	this.points = new Array();
	this.triangles = new Array();
	this.vertices = 0;
	this.polyName = '';
}

// initializes the polygon to be centered around the point center, which is
// a Point2D.
Polygon2D.prototype.buildNGon = function(sides, center) {
	this.points = new Array();
	this.triangles = new Array();
	this.vertices = sides;
	
	// make the points.
	if (this.vertices > 1){
		var theta = 0;
		var thetaStep = 2 * PI / sides;
		for (var i = 0; i < sides; i++){
			var x = polygonRadius * Math.cos(theta) + center.u;
			var y = polygonRadius * Math.sin(theta) + center.v;
			this.points[i] = new Point2D(x,y, true);		
			theta = theta + thetaStep;
		}
	}
	else {
		this.points[0] = new Point2D(center.u, center.v, true);
	}
	
	// triangulate the points.
	for (var i = 0; i < sides-2; i++){
		this.triangles[i] = new Array();
		this.triangles[i][0] = 0;
		this.triangles[i][1] = i+1;
		this.triangles[i][2] = i+2;
	}
}

Polygon2D.prototype.addPoint = function(p) {
	this.points[this.points.length] = p;
	this.vertices = this.vertices + 1;
}

Polygon2D.prototype.addTriangle = function(i0, i1, i2) {
	var n = this.triangles.length;
	var tri = new Array(i0, i1, i2)
	this.triangles[n] = tri;
}

Polygon2D.prototype.setStyle = function(strokeStyle, fillStyle, lineWidth) {
	this.strokeStyle = strokeStyle;
	this.fillStyle = fillStyle;
	this.lineWidth = lineWidth;
}

Polygon2D.prototype.draw = function() {
	var ctx = getContext();
	ctx.strokeStyle = this.strokeStyle;
	ctx.fillStyle = this.fillStyle;
	ctx.lineWidth = this.lineWidth;
	for (var i = 0; i < this.triangles.length; i++) {
		var tri = this.triangles[i];
		var p0 = this.points[tri[0]];
		var p1 = this.points[tri[1]];
		var p2 = this.points[tri[2]];
		
		ctx.beginPath();
		ctx.moveTo(p0.u, p0.v);
		ctx.lineTo(p1.u, p1.v);
		ctx.lineTo(p2.u, p2.v);
		ctx.closePath();
		ctx.fill();
		ctx.stroke();
	}

	for (var i = 0; i < this.points.length; i++) {
		this.points[i].draw();
	}
}